package org.aynu.orderservice.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.aynu.orderservice.common.OrderConstants;
import org.aynu.orderservice.entity.OrderEntity;
import org.aynu.orderservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.Instant;

/**
 * 订单超时任务
 *
 * @author 小粥
 * @since 2025/03/03
 */

@Component
@Slf4j
public class OrderTimeoutTask {

    /** 订购服务 */
    private final OrderService orderService;
    @Autowired
    public OrderTimeoutTask(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 检查订单超时
     *
     * @author 小粥
     * @since 2025/03/03
     */// 每小时检查一次
    @Scheduled(cron = "0 0 * * * ?")
    public void checkOrderTimeout() {
        log.info("开始检查超时订单...");
        orderService.list(new LambdaQueryWrapper<OrderEntity>()
                        .eq(OrderEntity::getStatus, OrderConstants.STATUS_WAIT_PAY)
                        .le(OrderEntity::getCreatedAt, Timestamp.from(Instant.now().minusSeconds(24 * 60 * 60))))
                .forEach(order -> {
                    try {
                        orderService.cancelOrderBySystem(order.getOrderId());
                        log.info("订单 {} 已超时，自动取消", order.getOrderId());
                    } catch (Exception e) {
                        log.error("订单 {} 超时取消失败: {}", order.getOrderId(), e.getMessage(), e);
                    }
                });
        log.info("超时订单检查完成");
    }
}